
package pl.genapp.stocksense;

import java.util.ArrayList;

import pl.genapp.appsense.R;
import pl.genapp.stocksense.libraries.FacebookHelper;
import pl.genapp.stocksense.libraries.SentGraph;
import pl.genapp.stocksense.libraries.TwitterHelper;
import pl.genapp.stocksense.others.LegendTypeChangeListener;
import pl.genapp.stocksense.others.StockSenseState;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class SettingsActivity extends PreferenceActivity {
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
		
		addPreferencesFromResource(R.xml.preference);
		
		setContentView(R.layout.activity_settings_layout);
		
		ListView list = (ListView) findViewById(android.R.id.list);
		
		Button clearAppData = new Button(this);
		
		clearAppData.setText("Clear application data");
		clearAppData.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				// clear shared prefs
				SettingsActivity.this.getSharedPreferences(LoginActivity.SHARED_PREFERENCE_STOCK_SENSE, 0).edit().clear().commit();
				
				// twitter
				SettingsActivity.this.getSharedPreferences(TwitterHelper.SHARED_PREFERENCE_TWITTER, 0).edit().clear().commit();
				
				//fb
				SettingsActivity.this.getSharedPreferences(FacebookHelper.SHARED_PREFERENCE_FACEBOOK, 0).edit().clear().commit();
								
				// watchlist
				// SettingsActivity.this.getSharedPreferences(StackSense.SHARED_PREFERENCE_WATCHLIST,
				// 0).edit().clear().commit();
				
			} 
		});
		
		list.addFooterView(clearAppData);
	}
	
	private OnSharedPreferenceChangeListener preferenceChangeListener = new  OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		
			if(key.equals(SentGraph.SP_LEGEND_POS_KEY)) {
				
				String legendType = sharedPreferences.getString(SentGraph.SP_LEGEND_POS_KEY, null);
				
				if(legendType != null) {
					
					ArrayList<LegendTypeChangeListener> legendTypeListeners =((StockSenseState)getApplication()).getLegendTypeChangelListeners();
					
					for(LegendTypeChangeListener listener: legendTypeListeners) {
						
						listener.onChange(SentGraph.getLegendTypeFromString(legendType));
						
					}
					
				}
				
			}
			
		}
		
	};
	
}
